
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: MainHelp.java 140 2009-11-04 03:44:16Z archie.cobbs $
 */

package org.dellroad.sidekar.xml;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

/**
 * Helper class for command line main() methods.
 */
final class MainHelp {

    private MainHelp() {
    }

    /**
     * Execute class main() method and handle exceptions and exit value.
     */
    public static void run(ExceptingRunnable runnable) {
        int exitValue = 1;
        try {
            runnable.run();
            exitValue = 0;
        } catch (Throwable t) {
            t.printStackTrace(System.err);
        } finally {
            System.exit(exitValue);
        }
    }

    /**
     * Configure log4j.
     */
    public static void setupLogging(Level logLevel) {
        if (logLevel == null)
            logLevel = Level.INFO;
        ConsoleAppender consoleAppender = new ConsoleAppender(new PatternLayout("%-5p [%t]: %m%n"), ConsoleAppender.SYSTEM_ERR);
        Logger.getRootLogger().removeAllAppenders();
        Logger.getRootLogger().addAppender(consoleAppender);
        Logger.getRootLogger().setLevel(logLevel);
    }
}

